<template>
  <div class="navLink">
    <div
      class="navItemDiv"
      v-for="(items, index) in Array.from($store.state.visitedTags)"
      :key="items.fullPath"
    >
      <router-link
        class="navItem"
        :to="items.fullPath"
        :class="{
          active: isActive(items, index),
          borderRadLeft: isActiveIndex - 1 == index,
          borderRadRight: isActiveIndex + 1 == index,
        }"
      >
        <span class="spanClo">{{ items.title }}</span>
        <span @click.prevent.stop="closeSelectedTag(items, index)">
          <close theme="filled" size="12" fill="#666" />
          <!-- :fill="isActive(items) ? '#fff' : '#666'" -->
        </span>
      </router-link>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isActiveIndex: 0,
    };
  },
  mounted() {
    // 获取到路由的 redirect 页且无法将其关闭
    // this.scrollInit()
  },
  methods: {
    scrollInit() {
      // 获取要绑定事件的元素
      const scrollDiv = document.getElementsByClassName('navLinkTab')[0]
      // 添加滚轮滚动监听事件，一般是用下面的方法，上面的是火狐的写法
      scrollDiv.addEventListener('mousewheel', handler, false)
      // 滚动事件的出来函数
      function handler(event) {
        // 获取滚动方向
        const detail = event.wheelDelta || event.detail
        // 定义滚动方向，其实也可以在赋值的时候写
        const moveForwardStep = 1
        const moveBackStep = -1
        // 定义滚动距离
        let step = 0
        // 判断滚动方向,这里的100可以改，代表滚动幅度，也就是说滚动幅度是自定义的
        if (detail < 0) {
          step = moveForwardStep * 20
        } else {
          step = moveBackStep * 20
        }
        // 对需要滚动的元素进行滚动操作
        scrollDiv.scrollLeft += step
      }
    },
    isActive(route, index) {
      if (route.path === this.$route.path) {
        this.isActiveIndex = index;
      }
      //当前地址栏路径是否与渲染的路径相同 样式匹配
      return route.path === this.$route.path;
    },
    closeSelectedTag(view, index) {
      let views = this.$store.state.visitedTags;
      this.$store.dispatch("closeTags", view).then(() => {
        // 此时的views是指的被删除后的visitedViews数组中存在的元素;
        if (this.isActive(view, index)) {
          // 当前关闭的标签是否是被选中的标签;
          const latestView = views.slice(-1)[0];
          if (latestView) {
            this.$router.push(latestView); //如果数组不为空则让选中的标签为紧邻关闭标签的那一个
          } else {
            this.$router.push("/"); //如果为空则页面跳转到/
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.navLink {
  // display: flex;
  white-space: nowrap;
}
.navItemDiv {
  display: inline-block;
  background: $bgColorF3F4F8;
}
.borderRadLeft {
  border-radius: 0 0 4px 0;
}
.borderRadRight {
  border-radius: 0 0 0 4px;
}
.navItem {
  color: $color999999;
  background: #fff;
  display: flex;
  padding: 2px 20px;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  .spanClo {
    margin-right: 8px;
  }
}

.active {
  background: $bgColorF3F4F8;
}
</style>
